﻿using System.IO;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;

public class UIAtlasToPng : EditorWindow
{
    public string outPath;
    public bool args = true;
    public static UIAtlas[] atlasArr;
    public static bool[] selectArr;

    [MenuItem("GameEditor/图集分解")]
    public static void Open()
    {
        GetFileList();
        GetWindow<UIAtlasToPng>("图集分解").Show();
    }

    void OnGUI()
    {
        args = EditorGUILayout.BeginToggleGroup("选择需要分解的图集", args);
        for (int i = 0; i < atlasArr.Length; i++)
        {
            selectArr[i] = EditorGUILayout.Toggle(atlasArr[i].name, selectArr[i]);
        }
        EditorGUILayout.EndToggleGroup();

        if (GUILayout.Button("开始分解", GUILayout.Width(80)))
        {
            Save(); Close();
        }
    }

    void Save()
    {
        outPath = EditorUtility.OpenFolderPanel("图片保存位置", Application.dataPath, "");
        for (int i = 0; i < atlasArr.Length; i++)
        {
            if (selectArr[i])
            {
                EditorUtility.DisplayProgressBar("正在分解", atlasArr[i].name, (i + 1f) / atlasArr.Length);
                for (int j = 0; j < atlasArr[i].spriteList.Count; j++)
                {
                    UISpriteData sprite = atlasArr[i].spriteList[j];
                    string path = outPath + "/" + atlasArr[i].name + "/" + sprite.name + ".png";
                    string dirName = Path.GetDirectoryName(path);
                    NGUISettings.currentPath = Path.GetDirectoryName(path);
                    UIAtlasMaker.SpriteEntry se = UIAtlasMaker.ExtractSprite(atlasArr[i], sprite.name);

                    if (se != null)
                    {
                        FileInfo info = new FileInfo(path);
                        info.Directory.Create();
                        byte[] bytes = se.tex.EncodeToPNG();
                        File.WriteAllBytes(path, bytes);
                        AssetDatabase.ImportAsset(path);

                        if (se.temporaryTexture)
                        {
                            DestroyImmediate(se.tex);
                        }
                    }
                }
            }
        }
    }

    static void GetFileList()
    {
        Object[] objs = Selection.GetFiltered(typeof(UIAtlas), SelectionMode.DeepAssets);
        atlasArr = new UIAtlas[objs.Length];
        selectArr = new bool[objs.Length];

        for (int i = 0; i < objs.Length; i++)
        {
            atlasArr[i] = (UIAtlas)objs[i];
            selectArr[i] = true;
        }
    }
}